<template>
	<view v-if="questions.length != 0">
		<view @click="isShow = true" class="topbox">{{number + 1}}/{{questions.length}}</view>
		<view class="contentbox">
			<view class="title">
				<span style="font-weight: normal;">({{ optype(questions[number].type) }})</span>
				{{questions[number].title}}
			</view>
			<view v-if="questions[number].type=='tian'">
				<input type="text" v-model="content" @input="changeInput"/>
				<hr>
			</view>
			<dan :arr="questions[number].options" :current="answers[number]" @fnc="radioChange" v-if="questions[number].type=='dan' || questions[number].type=='pan'"></dan>
			<duo :arr="questions[number].options" :record="record" @fnc="chooseboxChange" v-if="questions[number].type=='duo'"></duo>
		</view>
		<view class="btnbox">
			<button type="default" @click="calc(-1, questions[number-1].type)" v-show="number!=0">上一题</button>
			<button type="default" @click="calc(1, questions[number+1].type)" v-show="number!=questions.length-1">下一题</button>
		</view>
		<button  style="width: 60vw; margin-top: 3vh;" type="primary" @click="submit" v-if="answers[number] != '' && questions.length == answers.length && questions.length-1 == number">提交答题</button>
		<view class="cover" v-if="isShow" @click="isShow = false">
			<scroll-view scroll-y class="popbox">
				<text v-for="(item, index) in questions" :key="item.code" :class="{numberBtn: true, numberBtnBColor: answers[index]}" @click="numberCalc(index)">{{index+1}}</text>
			</scroll-view>
		</view>
		<view>
			<button type="primary" @tap="downloadFile()" class="down">下载练习</button>
			<view class="progress-container" v-if="isShowProgress">
				<view class="progress-box">
					<view class="text">文件下载中，请稍后......</view>
					<progress :percent="progress" show-info stroke-width="3" />
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import dan from "../../components/dan.vue"
	import duo from "../../components/duo.vue"
	
	import { getexercisequestions, setrecords, submitanswers, getwronglist, downloadtext, gettestquestions, settestrecords, submittestpaper } from '../../apis/questionAPI.js'
	
	export default {
		components: {
			dan,
			duo
		},
		data() {
			return {
				isShow: false,
				record: [], // 本道多选题记录，index对应A、B、C等序号，true表述被选中
				content: '', // 填空题记录
				answers: [''], // 本次答案
				number: 0, // 题号
				questions: [], // 问题
				type: '', // 类型
				subject: '', // 科目
				isSubmit: false, // 是否提交答案
				questionIds: [],
				// 下载练习的相关配置
				url: 'http://192.168.1.222:8000/questionlist.docx',
				isShowProgress: false,
				progress: 0,
				time: 0,
				scores: [],
				testpaper: ''
			}
		},
		computed:{
			optype() {
				return (type) => {
					switch (type) {
						case 'tian': return '填空'
						case 'duo': return '多选'
						case 'pan': return '判断'
						case 'dan': return '单选'
					}
				}
			}
		},
		onLoad(option) {
			let that = this
			this.type = option.type
			this.subject = option.subject
			if (option.time) {
				// 试卷
				this.time = option.time
				this.testpaper = option.testpaper
				gettestquestions({
					username: uni.getStorageSync('token'),
					time: option.time,
					isnew: option.isnew
				}).then(res => {
					that.questions = res.questions
					that.answers = res.answers
					that.questionIds = res.questionIds
					that.scores = res.scores
					// console.log(res.scores)
					if (res.isNew) {
						// 新开第一道是多选题做特殊处理
						if (res.questions[0].type == 'duo') {
							let arr = []
							for(let i=0; i<res.questions[0].options.length; i++) {
								arr.push(false)
							}
							that.record = arr
						}
					} else {
						// 恢复第一道题处理
						if (res.questions[0].type=='tian') {
							that.content = res.answers[0]
						} else if (res.questions[0].type=='duo') {
							let arr = []
							for (let j=0; j<res.questions[0].options.length; j++) {
								if (res.answers[0] != undefined && res.answers[0].indexOf(res.questions[0].options[j].code) !== -1) {
									arr.push(true)
								} else {
									arr.push(false)
								}
							}
							that.record = arr
						}
					}
				})
			} else {
				// 练习或组卷
				getexercisequestions({
					username: uni.getStorageSync('token'),
					type: option.type,
					subject: option.subject,
					num: option.num,
					isnew: option.isnew
				}).then(res => {
					that.questions = res.questions
					that.answers = res.answers
					that.questionIds = res.questionIds
					if (res.isNew) {
						// 新开第一道是多选题做特殊处理
						if (res.questions[0].type == 'duo') {
							let arr = []
							for(let i=0; i<res.questions[0].options.length; i++) {
								arr.push(false)
							}
							that.record = arr
						}
					} else {
						// 恢复第一道题处理
						if (res.questions[0].type=='tian') {
							that.content = res.answers[0]
						} else if (res.questions[0].type=='duo') {
							let arr = []
							// console.log(res.questions[0].options)
							// console.log(res.answers[0])
								for (let j=0; j<res.questions[0].options.length; j++) {
									if (res.answers[0] != undefined && res.answers[0].indexOf(res.questions[0].options[j].code) !== -1) {
										arr.push(true)
									} else {
										arr.push(false)
									}
								}
							that.record = arr
						}
					}
				})
			}
			
			
		},
		onUnload() {
			// console.log(this.answers)
			// 退出前未提交答案，记录答题
			if (!this.isSubmit) {
				if (this.type !== '试卷') {
					setrecords({
						username: uni.getStorageSync('token'),
						subject: this.subject,
						type: this.type,
						questionIds: this.questionIds,
						answers: this.answers
					})
				} else {
					settestrecords({
						username: uni.getStorageSync('token'),
						time: this.time,
						questionIds: this.questionIds,
						answers: this.answers
					})
				}
			}
		},
		methods: {
			// 修改单项选择答案
			radioChange(code) {
				this.answers.splice(this.number, 1, code)
				// console.log(this.answers)
			},
			// 修改多项选择答案
			chooseboxChange(index) {
				// console.log(this.record)
				this.record.splice(index, 1, !this.record[index]) 
				let str = ''
				for (let j=0; j<this.record.length; j++) {
					if (this.record[j]) {
						str = str + this.questions[this.number].options[j].code
					}
				}
				this.answers.splice(this.number, 1, str)
				// console.log(this.answers)
			},
			// 修改填空答案
			changeInput(e) {
				// this.content = e.detail.value
				this.answers[this.number] = e.target.value
				// console.log(this.answers)
			},
			// 改变题目
			calc(n, type) {
				// console.log(this.number, n, type)
				if (type == 'dan' || type == 'pan') {
					this.danCalc(n)
				} else if (type == 'duo') {
					this.duoCalc(n)
				} else {
					this.tianCalc(n)
				}
			},
			// 下一题是单选/判断的处理
			danCalc(n) {
				if (n==1 && this.number+1 == this.answers.length) {
					this.answers.push('')
				}
				this.number = this.number + n
			},
			// 下一题是多选的处理
			duoCalc(n) {
				this.number = this.number + n
				if (this.questions[this.number].type == 'duo' && this.answers.length == this.number) {
					let arr = []
					for(let i=0; i<this.questions[this.number].options.length; i++) {
						arr.push(false)
					}
					this.record = arr
					this.answers.push('')
				} else {
					let arr = []
					for (let j=0; j<this.questions[this.number].options.length; j++) {
						if (this.answers[this.number] != undefined &&  this.answers[this.number].indexOf(this.questions[this.number].options[j].code) !== -1) {
							arr.push(true)
						} else {
							arr.push(false)
						}
					}
					this.record = arr
				}
			},
			// 下一题是填空的处理
			tianCalc(n) {
				this.number = this.number + n
				if (n==1 && this.answers.length == this.number) {
					this.answers.push('')
					this.content = ''
				} else {
					this.content = this.answers[this.number]
				}
			},
			// 从题目需要列表中改变题目的处理
			numberCalc(index) {
				let length = index - this.number
				// 判断选择的题是否有答案
				if (length > 0 && index >= this.answers.length) {
					for (let i=this.number+1; i<=index; i++) {
						this.answers.push('')
					}
					if (this.questions[index].type == 'duo') {
						let arr = []
						for(let j=0; j<this.questions[index].options.length; j++) {
							arr.push(false)
						}
						this.record = arr
					} else if (this.questions[index].type == 'tian') {
						this.content = ''
					}
				} else {
					// 有答案恢复记录
					if (this.questions[index].type == 'duo') {
						let arr = []
						for (let j=0; j<this.questions[index].options.length; j++) {
							if (this.answers[index] != undefined && this.answers[index].indexOf(this.questions[index].options[j].code) !== -1) {
								arr.push(true)
							} else {
								arr.push(false)
							}
						}
						this.record = arr
					} else if (this.questions[index].type == 'tian') {
						this.content = this.answers[index]
					}
				}
				this.number = index
				console.log(this.answers)
			},
			// 提交答案
			submit() {
				this.isSubmit = true
				let errorIndexs = []
				let grades = []
				// 记录错题在questions中的编号
				for (let i=0; i<this.questions.length; i++) {
					if (this.answers[i] != this.questions[i].answer) {
						errorIndexs.push(i)
						grades.push(0)
					} else {
						grades.push(1)
						
					}
				}
				let that = this
				if (this.type != '试卷') {
					submitanswers({
						username: uni.getStorageSync('token'),
						type: this.type,
						subject: this.subject,
						answers: this.answers,
						errorIndexs,
						questionIds: this.questionIds,
						grades
					}).then(res => {
						// console.log("111")
						if (errorIndexs.length != 0) {
							getwronglist({
								username: uni.getStorageSync('token')
							}).then(r => {
								// console.log("222")
								that.$store.dispatch('setwronglist', r.wronglist)
								// console.log(res.id)
								uni.redirectTo({
									url: `/pages/grade/grade?time=${res.time}&type=${that.type}`,
									// url: `/pages/grade/grade?type=exercise`,
								})
							})
						} else {
							uni.redirectTo({
								url: `/pages/grade/grade?time=${res.time}&type=${that.type}`,
								// url: `/pages/grade/grade?type=exercise`,
							})
						}
					})
				} else {
					submittestpaper({
						username: uni.getStorageSync('token'),
						time: this.time,
						answers: this.answers,
						errorIndexs,
						questionIds: this.questionIds,
						grades,
						scores: this.scores
					}).then(res => {
						// console.log("111")
						if (errorIndexs.length != 0) {
							getwronglist({
								username: uni.getStorageSync('token')
							}).then(r => {
								// console.log("222")
								that.$store.dispatch('setwronglist', r.wronglist)
								// console.log(res.id)
								uni.redirectTo({
									url: `/pages/grade/grade?time=${res.time}&type=${that.type}`,
									// url: `/pages/grade/grade?type=exercise`,
								})
							})
						} else {
							uni.redirectTo({
								url: `/pages/grade/grade?time=${res.time}&type=${that.type}`,
								// url: `/pages/grade/grade?type=exercise`,
							})
						}
					})
				}
				
			},
			// 下载练习
			downloadFile() {
				const that = this
				uni.showModal({
					title: '确定下载本次做题文档？',
					confirmColor:'#3A3A3A',
					cancelColor:'#999999',
					confirmText:'确定',
					success: function (res1) {
						// console.log(res.content)
						let item = {
							questionIds: that.questionIds
						}
						if (that.type == '试卷') {
							item.scores = that.scores
							item.testpaper = that.testpaper
						} else {
							item.subject= that.subject
							item.type= that.type
						}
						if (res1.confirm) {
							downloadtext(item).then(res2 => {
								const downloadTask = uni.downloadFile({
									url: that.url,
									success: res => {
										if (res.statusCode === 200) {
											this.isShowProgress = false;
											// console.log('下载成功');
										}
										uni.saveFile({
											tempFilePath: res.tempFilePath,
											success: function(red) {
												that.isShowProgress = false;
												uni.showModal({
													title: '提示',
													content: '文件已保存：' + red.savedFilePath,
													cancelText: '我知道了',
													confirmText: '打开文件',
													success: function (res) {
														if (res.confirm) {
															uni.openDocument({
																filePath: red.savedFilePath,
																success: (sus) => {
																	// console.log('成功打开');
																}
															})
														}
													}
												});
											}
										});
									}
								})
								
								downloadTask.onProgressUpdate((res) => {
									if(res.progress > 0) {
										that.isShowProgress = true;
									}
									that.progress = res.progress;
									// console.log('下载进度：' + res.progress);
									// console.log('已下载长度：' + res.totalBytesWritten);
									// console.log('文件总长度：' + res.totalBytesExpectedToWrite);
								})
							})
						}
					}
				})
			},
			
		}
	}
</script>

<style lang="less" scoped>
	.numberBtn {
		display: inline-block;
		border: 1px solid #000;
		border-radius: 50%;
		line-height: 8vw;
		width: 8vw;
		height: 8vw;
		margin: 1vw;
		text-align: center;
	}
	.numberBtnBColor {
		background-color: rgba(0,0,255,.5);
	}
	.topbox {
		width: 94vw;
		background-color: #f8f8f8;
		height: 5vh;
		text-align: center;
		line-height: 5vh;
		margin: 2vh auto;
		font-size: 2.8vh;
	}
	.contentbox {
		box-sizing: border-box;
		width: 94vw;
		background-color: #f8f8f8;
		padding: 1vh 3vw;
		margin: 2vh auto;
		font-size: 2.8vh;
		
		.title {
			margin-bottom: 2vh;
			font-weight: bold;
		}
		
		input {
			font-size: 2.8vh;
		}
	}
	.btnbox {
		display: flex;
		width: 94vw;
		margin: 2vh auto;
		button {
			width: 40vw;
		}
	}
	.cover {
		text-align: center;
		position: absolute;
		top: 0;
		left: 0;
		width: 100vw;
		height: 100%;
		background-color: rgba(238, 238, 238, .9);
		
		.popbox {
			position: absolute;
			max-width: 74vw;
			max-height: 70vh;
			// overflow-y: ;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -60%);
			z-index: 10;
			background-color: #f8f8f8;
			padding: 2vh;
			border: 1px solid rgba(0,0,0,.2);
			border-radius: 10px;
			
			button {
				margin-top: 1vh;
			}
		}
	}
	.down {
		position: fixed;
		bottom: 3vh;
		left: 50%;
		transform: translateX(-50%);
	}
	.progress-container {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 99;
		background: rgba(0, 0, 0, .2);
		width: 750rpx;
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
		.progress-box {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 30rpx;
			.text {
				margin-bottom: 20rpx;
			}
		}
	}
</style>
